package com.wolfman.uploadfile.controller;

import com.wolfman.uploadfile.components.RedisComponent;
import com.wolfman.uploadfile.po.FileDownload;
import com.wolfman.uploadfile.po.FileUpload;
import com.wolfman.uploadfile.service.FileDownloadService;
import com.wolfman.uploadfile.vo.Result;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.net.URLEncoder;


/**
 * @Title
 * @Description
 * @Author WolfMan
 * @Date 2021/8/23 13:57
 * @Email 2370032534@qq.com
 */
@Controller
@RequestMapping("/download")
public class DownloadFileController {

    @Resource
    FileDownloadService fileDownloadService;
    @Resource
    RedisComponent redisComponent;

    /**
     * 获取文件上传id
     *
     * @return
     */
    @GetMapping("/getDownloadId")
    @ResponseBody
    public Result getDownloadId() {
        //调用service存储文件基本信息
        FileDownload fileDownload = new FileDownload();
        fileDownload.setFilename("");
        fileDownload.setFilePath("");
        fileDownload.setUploadProgress(0D);
        fileDownloadService.insertOne(fileDownload);
        //初始化暂停
        redisComponent.set("download_File_pause->" + fileDownload.getId() + ":", false);
        return Result.success(fileDownload, "成功获取!");
    }

    /**
     * 下载文件
     *
     * @param response
     * @throws Exception
     */
    @PostMapping("/downloadFile")
    public void downloadFile(FileDownload fileDownload, HttpServletResponse response) throws Exception {
        // 获取文件
        File file = new File(new File("").getAbsolutePath() + "/src/main/resources/static/download/1.jpg");
        //文件名
        String fileName = file.getName();
        // 清空缓冲区，状态码和响应头(headers)
        response.reset();
        // 设置ContentType，响应内容为二进制数据流，编码为utf-8，此处设定的编码是文件内容的编码
        response.setContentType("application/octet-stream;charset=utf-8");
        // 以（Content-Disposition: attachment; filename="filename.jpg"）格式设定默认文件名，设定utf编码，此处的编码是文件名的编码，使能正确显示中文文件名
        response.addHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
        // 获取输入流
        BufferedInputStream bs = new BufferedInputStream(new FileInputStream(file));
        // 获取输出流
        OutputStream os = response.getOutputStream();
        // 获取文件的大小
        double totalSize = bs.available();
        double percent;
        boolean isPause;
        byte[] buffer = new byte[1024];
        while (bs.read(buffer) != -1) {
            //睡眠延时
            Thread.sleep(100);
            //下载文件
            os.write(buffer);
            //计算下载进度
            percent = (1 - bs.available() / totalSize) * 100;
            //保存下载进度
            redisComponent.set("download_File_percent->" + fileDownload.getId() + ":", percent);
            isPause = (boolean) redisComponent.get("download_File_pause->" + fileDownload.getId() + ":");
            if (isPause) {
                break;
            }
        }
        // 关闭流
        bs.close();
        os.close();
        // 保存数据库
        fileDownload.setFilename(fileName);
        fileDownload.setFilePath("/download/" + fileName);
        fileDownloadService.updateInfo(fileDownload);
        //保存进度
        fileDownloadService.updateProcess(fileDownload);
    }

    /**
     * 获取实时长传进度
     *
     * @return
     */
    @ResponseBody
    @GetMapping("/getPercent")
    public Result getPercent(FileUpload fileDownload) {
        Double percent = (Double) redisComponent.get("download_File_percent->" + fileDownload.getId() + ":");
        if (percent == null) {
            percent = 0D;
        }
        return Result.success(String.format("%.2f", percent), "请求成功！");
    }

    /**
     * 暂停文件上传
     *
     * @return
     */
    @ResponseBody
    @GetMapping("/pauseDownload")
    public Result pauseUpload(FileDownload fileDownload) {
        redisComponent.set("download_File_pause->" + fileDownload.getId() + ":", true);
        return Result.success(null, "暂停成功！");
    }

    /**
     * 继续文件上传
     *
     * @return
     */
    @ResponseBody
    @GetMapping("/continueDownload")
    public Result continueUpload(FileDownload fileDownload) throws Exception {
        //获取文件
        FileDownload f = fileDownloadService.selectById(fileDownload);
        //获取文件绝对路径
        String filePath = new File("").getAbsolutePath() + "/src/main/resources/static/download/" + f.getFilename();
        //获取偏移量
        long available = new FileInputStream(filePath).available();
        //通过随机流上传
        return Result.success(null, "继续上传！");
    }

}
